#include "campus_chat_server.h"
#include "../log/campus_logger.h"

CampusChatServer::CampusChatServer(int port, ChatServerObserver *observer):
    CampusWssServer(port),
    observer_(observer)
{
}

CampusChatServer::~CampusChatServer()
{
}

void CampusChatServer::on_open(server *s, websocketpp::connection_hdl hdl)
{
    CampusLogger::info("chat_server:on_open ");
    CampusWssServer::on_open(s, hdl);
}

void CampusChatServer::on_close(server *s, websocketpp::connection_hdl hdl)
{
    CampusLogger::info("chat_server:on_close ");
    CampusWssServer::on_close(s, hdl);
}

void CampusChatServer::on_message(server *s, websocketpp::connection_hdl hdl, message_ptr msg)
{
    CampusLogger::info("chat_server:on_message {}",msg->get_payload());
    
    json JMsg = json::parse(msg->get_payload());
    std::string cmd = JMsg["cmd"];
    if(cmd == SIGNAL_TYPE_CHAT_JOIN)
    {
        observer_->handleChatJoin(hdl, JMsg);
    }
    else if(cmd == SIGNAL_TYPE_CHAT_MSG)
    {
        observer_->handleChatMsg(hdl, JMsg);
    }
}

void CampusChatServer::on_fail(websocketpp::connection_hdl hdl)
{
    CampusLogger::info("chat_server: on_fail ");
    CampusWssServer::on_fail(hdl);
}
